package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Component;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/1 23:21
 *
 *   调用内部方法生成唯一的数字
   */
@Component
public class Idworker {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Long getNextId(String collName){

        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        // 自曾
        update.inc("seqId", 1);

        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);

        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getSeqId();
    }
}
